package com.adcc.ags.cgw.service;

import com.adcc.ags.cgw.entity.msg.CGWMsg;
import com.adcc.ags.cgw.entity.msg.MsgType;
import com.adcc.ags.cgw.entity.msg.TrafficMsg;
import com.adcc.ags.cgw.proxy.MsgProxy;
import com.adcc.ags.cgw.proxy.UpLinkDispatchProxy;
import com.adcc.ags.cgw.utils.Constant;
import com.adcc.utility.log.Log;
import com.adcc.utility.msg620.ACARS620Verification;


/**
 * 报文校验服务
 */
public class MsgVerificationServiceImpl extends MsgVerificationService {

    @Override
    protected boolean verify(String message) {

        // maxLength为0，则不进行长度校验
        if (UpLinkDispatchProxy.getInstance().getMaxLength() == 0) {
            return ACARS620Verification.verify(message);
        } else {
            return ACARS620Verification.verify(message, UpLinkDispatchProxy.getInstance().getMaxLength());
        }
    }

    @Override
    public void onReceive(Object message) {
        super.onReceive(message);

        try {
            CGWMsg cgwMsg = (CGWMsg)message;
            if (cgwMsg != null) {

                // 对上行报文进行校验，如果620校验失败不上发报文
                if (cgwMsg.getType() == MsgType.UPLINK) {
                    byte[] buffer = cgwMsg.getMsg().getContent();
                    if (!verify(new String(buffer, 0, buffer.length))) {
                        Log.error(MsgVerificationService.class.getName(), "verify uplink message failed from:" + cgwMsg.getUser().get().getName() + "\r\n" + cgwMsg.getMsg().toString());

                        // 消息入库处理
                        MsgProxy.getInstance().getMsgSaveActor().tell(new TrafficMsg(cgwMsg.getId(),Constant.ERROR_CODE_VERIFYFAILED,""),this.getSelf());
                        return;
                    }
                }
                MsgProxy.getInstance().getMsgFilterActor().tell(cgwMsg, this.getSelf());
            } else {
                Log.error(MsgVerificationService.class.getName(),"receive invalid uplink message");
                unhandled(message);
            }
        } catch (Exception ex) {
            Log.error(MsgVerificationService.class.getName(), "onReceive() error", ex);
        }
    }
}
